package com.hc.ureport.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 用于过滤未登陆用户访问管理内容的拦截器
 * 权限和个人信息保存到缓存中
 */
@Component
public class RestPermissionInterceptor implements HandlerInterceptor {

    public static final String DEFAULT_CHARSET = "utf-8";
    public static final Long MAX_TIMESTAMP_TIMEOUT = 5 * 60 * 1000L;


    private static final List<String> whiteList = Arrays.asList(
            "/login"

    );

    private static final List<String> manageWhiteList = Arrays.asList(
            "/manager/ping",
            "/manager/admin/login",
            "/manager/admin/logout",
            "/manager/admin/update",
            "/manager/admin/updatePassword",
            "/manager/admin/uploadImage",
            "/manager/templeAccount/templeList"

    );


    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object obj, Exception e) throws Exception {
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object obj, ModelAndView mav) throws Exception {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        request.setCharacterEncoding(DEFAULT_CHARSET);
        response.setCharacterEncoding(DEFAULT_CHARSET);
        //判定消息来源，只允许管理端发来的消息请求
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());

        String method = request.getMethod();
        if (RequestMethod.OPTIONS.toString().equalsIgnoreCase(method)) {
            return true;
        }

        if (whiteList.contains(url)) {
            return true;
        }

        if (url.startsWith("/api/")) {
//            //数据的防多次被调用
//            long timeStamp = CommonUtils.toLong(request.getParameter("timeStamp"), 0);
//            if (Math.abs(System.currentTimeMillis() - timeStamp) > MAX_TIMESTAMP_TIMEOUT) {
//                //请求参数异常
//                CompressUtil.compressToJsonOut(response, FastJsonUtils.toJsonString(getErrorResultModel(Result.ParamsTimeStampError)));
//                return false;
//            }
        }

//        String token = request.getHeader(Constants.KEY_TOKEN);

        if (url.toLowerCase().startsWith("/manager/")) {
            if (manageWhiteList.contains(url)) {
                return true;
            }

//            TtAdminBean adminModel = null;
//            //从请求中获取参数
//            if (!CommonUtils.isEmpty(token)) {
//                adminModel = adminSessionCache.get(token, TtAdminBean.class);
//            } else if (request.getSession().getAttribute(Constants.SessionAttributes.Admin) != null) {
//                adminModel = (TtAdminBean) request.getSession().getAttribute(Constants.SessionAttributes.Admin);
//            }
//
//            if (adminModel != null) {
//                return true;
//            } else {
//                CompressUtil.compressToJsonOut(response, FastJsonUtils.toJsonString(getErrorResultModel(Result.SessionError)));
//                return false;
//            }
        }

        // 其余过滤条件

        return true;

    }

//    private HttpResultModel getErrorResultModel(Result result) {
//        HttpResultModel<String> resultModel = new HttpResultModel<>();
//        resultModel.setCode(result.getCode());
//        resultModel.setMsg(result.getMessage());
//        resultModel.setSendTime(System.currentTimeMillis());
//        return resultModel;
//    }

}
